package zsc.ruanc.practicaltraining.schduletask;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import zsc.ruanc.practicaltraining.mapper.ArticleMapper;
import zsc.ruanc.practicaltraining.mapper.UserMapper;
import zsc.ruanc.practicaltraining.model.domain.TArticle;
import zsc.ruanc.practicaltraining.model.vo.AdminEmailVo;
import zsc.ruanc.practicaltraining.model.vo.EmailVo;
import zsc.ruanc.practicaltraining.service.ArticleService;
import zsc.ruanc.practicaltraining.service.EmailService;
import zsc.ruanc.practicaltraining.service.RabbitMQService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class ArticleTask {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RabbitMQService rabbitMQService;


    private long standard = 60 * 60 * 24 * 1000; // 48小时

    // 对于发布48小时还未通过审核的文章系统会自动让其通过
    // 推迟一小时执行 每两个小时执行一次
    @Scheduled(initialDelay = 3600000, fixedRate = 7200000)
    public void articleVerify() {

        List<TArticle> list = articleMapper.checkVerify();
        Date date = new Date();

        ArrayList<Integer> idList = new ArrayList();

        for (TArticle item : list) {

            long diff = date.getTime() - item.getCreated().getTime();

            if (diff >= standard) {
                articleService.updateFlag(item.getId(), true);
                idList.add(item.getId());
            }

            // 缓解服务器压力 不要执行的太快
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

        String format = "因48小时还未审核， %s 文章已自动通过审核，总计 %s 篇文章，如有异议，请及时复审！！！";

        String info = String.format(format, idList.toString(), String.valueOf(idList.size()));

        // 找到所有管理员发消息
        Integer[] adminId = userMapper.findAdmin();

        for (int item : adminId) {
            rabbitMQService.adminMailbox(item, info);

            // 缓解服务器压力 不要执行的太快
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


    }

}
